import React from 'react';
import { Form, Input, Select, Button, Row, Col, Upload, message, Divider, Checkbox, Modal, Space } from 'antd';
import { LoadingOutlined, CloseOutlined, PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { connect } from 'umi';
import UploadUtil from '@/components/UploadUtil';
import PswUpdate from './pswUpdate';
import imgAvatar from '@/assets/avatar.png';

const { Search } = Input;
const { confirm } = Modal;
class UserEdit extends React.Component<any, any> {
    constructor(props: any) {
        super(props);
        this.state = {
            loading: false,
            visible: false,
            imageUrl: '',
            imgList: [],
            disabled: true,
            datas: {},
            Roles: [],
            RoleSelect: [],
        }
    }
    formRef: any = React.createRef();

    componentDidMount() {
        this.initData();
        this.fetchRoles();
    }
    initData = () => {
        this.props.dispatch({
            type: 'Department/getAll',
        }).then(() => {
            this.getCurrentUser();
        });
    }
    getCurrentUser = () => {
        this.props.dispatch({
            type: "Abp/getCurrentUser",
        }).then(() => {
            this.fetchUser();
        })
    }
    fetchUser = () => {
        const { currentUser } = this.props;
        if (currentUser) {
            this.props.dispatch({
                type: 'Abp/get',
                payload: { Id: currentUser?.id },
                control: 'User',
            }).then(() => {
                let datas = this.props.response?.result;
                if (datas) {
                    var imageUrl = imgAvatar;
                    if (datas.avater)
                        imageUrl = datas.avater;
                    this.setState({ imageUrl, datas })
                    this.formRef.current.setFieldsValue({ user: datas });
                }
            });
        }
    }
    fetchRoles = () => {
        this.props.dispatch({
            type: "Abp/getAll",
            payload: { SkipCount: 0, MaxResultCount: 100 },
            control: 'Role',
        }).then(() => {
            var resp = this.props.response?.result;
            if (resp) {
                var Roles = this.props.response.result.items;
                this.setState({ Roles })
            }
        });
    }

    onFinish = async (values: any) => {
        this.setState({ loading: true });
        var user = values.user;
        var act = "Abp/update";
        if (user.id == 0 || !user.id) {
            act = "Abp/create";
            user.password = "123456";
        }
        if (this.state.imageUrl) {
            user.avater = this.state.imageUrl;
        }
        this.props.dispatch({
            type: act,
            payload: user,
            control: 'User',
        }).then(() => {
            var resp = this.props.response;
            if (resp.success) {
                message.success('保存成功！');
            }
            else {
                message.error('保存错误，请联系管理员！');
            }
            this.setState({ loading: false });
        });
    };
    onChange = (value: any) => {
        console.log(value);
    }
    handleChange = (info: any) => {
        if (info.file.status === 'done' && info.file.response) {
            this.setState({
                imageUrl: info.file.response.result
            })
        }
    };
    handleAdd = () => {
        this.setState({ disabled: false, imageUrl: null, imgList: [] });
        this.formRef.current.resetFields();
    }
    handleDel = () => {
        const { datas } = this.state;
        if (datas.userName == "admin") {
            message.error('管理员用户不允许删除！');
        }
        else {
            this.props.dispatch({
                type: "Abp/delete",
                payload: { Id: datas.id },
                control: 'User',
            }).then(() => {
                var resp = this.props.response;
                if (resp.success) {
                    message.success('删除成功！');
                    this.props.refresh();
                    this.formRef.current.resetFields();
                }
                else {
                    message.error('删除错误，请联系管理员！');
                }
            })
        }

    }
    delConfirm = () => {
        var _this = this;
        confirm({
            title: '警告',
            icon: <ExclamationCircleOutlined />,
            content: '删除后将不可恢复，确定删除？',
            onOk() {
                _this.handleDel();
            },
            onCancel() { },
        });
    }
    getUserByName = (value: any) => {
        if (value) {
            this.props.dispatch({
                type: "Abp/getAll",
                payload: { SkipCount: 0, MaxResultCount: 9999 },
                control: 'User',
            }).then(() => {
                var resp = this.props.response.result.items;
                var obj = resp.filter((o: any) => o.userName == value)[0];
                if (obj) {
                    if (obj && obj.avater)
                        this.setState({ imageUrl: UploadUtil.imgServ + obj.avater });
                    this.formRef.current.setFieldsValue({ user: obj });
                }
                else {
                    message.warning('无此用户');
                }
            });
        }
    }
    switchModal = (visible: boolean) => {
        this.setState({ visible });
    }
    selectRoleChange = (value: string[]) => {
        var obj = this.formRef.current.getFieldsValue();
        obj.user.authorities = value.join(",")
        this.formRef.current.setFieldsValue({ user: obj.user });
    }
    render() {
        const layout = {
            labelCol: { span: 6 },
            wrapperCol: { span: 10 },
        };
        const { imageUrl, loading, Roles } = this.state;
        const { currentUser } = this.props;
        const uploadButton = (
            <div>
                {loading ? <LoadingOutlined /> : <PlusOutlined />}
                <div className="ant-upload-text">Upload</div>
            </div>
        );
        return (
            <div>
                <Space>
                    <Button type="primary" icon={<PlusOutlined />} onClick={this.handleAdd}>新增</Button>
                    <Button danger icon={<CloseOutlined />} onClick={this.delConfirm}>删除</Button>
                    <Button danger onClick={() => this.switchModal(true)}>更改密码</Button>
                </Space>
                <Divider />
                <Row gutter={16}>
                    <Col span={16}>
                        <Form {...layout} ref={this.formRef} onFinish={this.onFinish} >
                            <Form.Item
                                name={['user', 'userName']}
                                label="用户名"
                                rules={[{ required: true, message: "请输入用户名" }]}>
                                {/* <Input disabled={this.state.disabled} style={{ width: '50%' }} /> */}
                                <Search
                                    placeholder="输入或选择用户"
                                    disabled={this.state.disabled}
                                    onSearch={value => this.getUserByName(value)}
                                    style={{ width: '50%' }}
                                />
                            </Form.Item>
                            <Form.Item name={['user', 'deptID']} label="所属机构">
                                <Select
                                    style={{ width: '50%' }}
                                    showSearch
                                    placeholder="请选择机构"
                                    filterOption={(input, option: any) =>
                                        option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                    }
                                >
                                    {
                                        this.props.departments?.map((item: any) => {
                                            return (<Select.Option key={item.id} value={item.id}>{item.deptName}</Select.Option>)
                                        })
                                    }

                                </Select>
                            </Form.Item>
                            <Form.Item name={['user', 'id']} style={{ display: 'none' }}>
                                <Input />
                            </Form.Item>
                            <Form.Item name={['user', 'avater']} style={{ display: 'none' }}>
                                <Input />
                            </Form.Item>
                            <Form.Item label="用户身份" name={['user', 'authorities']} rules={[{ required: true }]}>
                                <Select>
                                    {
                                        Roles.map((item: any) => {
                                            return (
                                                <Select.Option
                                                    key={item.id}
                                                    value={item.normalizedName}>{item.displayName}
                                                </Select.Option>
                                            )
                                        })
                                    }
                                </Select>
                            </Form.Item>
                            <Form.Item
                                name={['user', 'empID']}
                                label="用户编号"
                                rules={[{ required: true, message: "请输入或选择员工" }]}>
                                <Input style={{ width: '50%' }} />
                            </Form.Item>
                            <Form.Item label="姓名">
                                <Input.Group compact>
                                    <Form.Item
                                        noStyle
                                        name={['user', 'name']}
                                        rules={[{ required: true, message: "请输入姓" }]} >
                                        <Input style={{ width: '50%' }} placeholder="姓" />
                                    </Form.Item>
                                    <Form.Item
                                        noStyle
                                        name={['user', 'surname']}
                                        rules={[{ required: true, message: "请输入名" }]}>
                                        <Input style={{ width: '50%' }} placeholder="名" />
                                    </Form.Item>
                                </Input.Group>
                            </Form.Item>

                            <Form.Item
                                name={['user', 'fullName']}
                                label="用户姓名"
                                rules={[{ required: true, message: "请输入员工姓名" }]}>
                                <Input style={{ width: '50%' }} />
                            </Form.Item>
                            <Form.Item
                                name={['user', 'address']}
                                label="联系地址">
                                <Input />
                            </Form.Item>
                            <Form.Item name={['user', 'telphone']} label="联系电话">
                                <Input />
                            </Form.Item>
                            <Form.Item name={['user', 'emailAddress']}
                                rules={[{ required: true, message: "请输入电子邮件" }]}
                                label="电子邮件">
                                <Input />
                            </Form.Item>
                            <Form.Item name={['user', 'roleNames']} label="系统角色">
                                <Select mode="multiple">
                                    {
                                        Roles.map((item: any) => {
                                            return (
                                                <Select.Option
                                                    key={item.id}
                                                    value={item.normalizedName}>{item.displayName}
                                                </Select.Option>
                                            )
                                        })
                                    }
                                </Select>
                            </Form.Item>
                            <Form.Item name={['user', 'isActive']} label="激活" valuePropName="checked">
                                <Checkbox></Checkbox>
                            </Form.Item>
                            <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 6 }}>
                                <Button type="primary" htmlType="submit" loading={this.state.loading}>保存</Button>
                            </Form.Item>
                        </Form>
                    </Col>
                    <Col span={8}>
                        <p>头像</p>
                        <Upload
                            action={UploadUtil.actionURL}
                            headers={{
                                'Authorization': UploadUtil.accessToken,
                            }}
                            data={{
                                objectId: currentUser.id,
                                objectName: 'user',
                                objectField: 'avater'
                            }}
                            name="files"
                            listType="picture-card"
                            className="avatar-uploader"
                            showUploadList={false}
                            beforeUpload={UploadUtil.beforeUpload}
                            onChange={this.handleChange}
                        >
                            {imageUrl ? <img src={UploadUtil.imgServ+imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                        </Upload>
                        <Modal
                            title={<b>密码更改</b>}
                            visible={this.state.visible}
                            onOk={() => this.switchModal(false)}
                            onCancel={() => this.switchModal(false)}
                            footer={null}
                            destroyOnClose={true}>
                            <PswUpdate userId={this.state.datas.id} />
                        </Modal>
                    </Col>
                </Row>
            </div>
        )
    }
}
export default connect(({ Abp, Department }: API.IConnectState) => ({
    response: Abp.response,
    currentUser: Abp.currentUser,
    departments: Department.departments,
}))(UserEdit);